'use strict';
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');
var mkdirp = require('mkdirp');

var domain = 'http://www.enterdesk.com';
var url = 'http://www.enterdesk.com/view/74/5184_0.html';
var host = 'http://www.enterdesk.com/view/{cat}_0.html';

var dir = './static/img';

var cats = [{
	cat: 74,
	id: 5184
}, {
	cat: 76,
	id: 5242
}, {
	cat: 74,
	id: 15828
}, {
	cat: 77,
	id: 301
}, {
	cat: 74,
	id: 5419
}, {
	cat: 76,
	id: 6150
}, {
	cat: 77,
	id: 2749
}, {
	cat: 74,
	id: 258
}, {
	cat: 75,
	id: 307
}];


cats.forEach(function(v) {
	mkdirp(dir + '/' + v.id);

	pullCat(v.cat, v.id);
})

function pullCat(cat, id) {
	var src = host.replace('{cat}', cat + '/' + id);

	start(src)
}

var numcache = {};

function start(url) {
	console.log('start ', url);

	let tempstr = url.split('view/')[1],
		i = tempstr.lastIndexOf('/'),
		cat = tempstr.substring(0, i),
		id = tempstr.substr(i + 1).split('_')[0];

	request(url, function(err, res, body) {
		if (err) {
			console.log('request err!');
			return;
		}
		if (res.statusCode == 200) {
			var $ = cheerio.load(body),
				src = '';

			src = $('.down_showpic img').attr('src');

			numcache[cat + '/' + id] = numcache[cat + '/' + id] || 0;
			console.log('start download');
			download(src, cat, id);
			console.log('download ok!', src);


			var num = numcache[cat + '/' + id];
			num++;
			var next = url.split('_')[0] + '_' + num + '.html';

			console.log('next', next);
			if (!next) return;

			setTimeout(start(next), 3000);


		}
	})
}


function download(src, cat, id) {
	if (!src) return;

	var filename = src.substr(src.lastIndexOf('/') + 1);

	request.head(src, function(err, res, body) {
		request(src).pipe(fs.createWriteStream(dir + '/' + id + '/' + filename))
	})
}